// packageX/activity_create/activity_create.js
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 表单数据
    formData: {
      commerce_circle_id: '', // 圈子id
      title: '', // 活动名称
      thumb: '', // 活动图片
      registration_time: '', // 报名开始时间
      registration_end_time: '', // 报名结束时间
      start_time: '', // 活动开始时间
      end_time: '', // 活动结束时间
      cash: '', // 活动费用
      limit: '', // 限制名额
      province_id: '', // 省id
      city_id: '', // 市id
      district_id: '', // 区县id
      address: '', // 详细地址
      fileList: [] // 上传文件列表
    },
    // 日期选择器相关
    currentDate: new Date().getTime(),
    minDate: new Date().getTime() - 1000 * 60 * 60 * 24,
    showRegistrationStartPicker: false,
    showRegistrationEndPicker: false,
    showActivityStartPicker: false,
    showActivityEndPicker: false,
    // 地区选择器相关
    showAreaPicker: false,
    regionText: '请选择地区',
    pickerValue: [0, 0, 0],
    selectAddressData: [{}, {}, {}],
    provinceData: [],
    cityData: [],
    districtData: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 从页面参数中获取圈子id
    if (options.id) {
      this.setData({
        'formData.commerce_circle_id': options.id
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 页面显示时的处理逻辑
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    app._getNetWork({
      url: app.getNetAddresss("member.member-address.address"),
      success: function (res) {
        var response = res.data;
        var provinceData = response.data.province;
        var cityData = response.data.city;
        var districtData = response.data.district;
        that.setData({
          provinceData: provinceData,
          cityData: cityData,
          districtData: districtData
        });
        that._setAreaList()
      },
      fail: function (res) {},
      state: true
    });
  },
  
  // 在_getDistrictData方法之后添加设置areaList的逻辑
  _setAreaList: function() {
    // 构建areaList并设置到data中
    const areaList = this.getAreaList();
    this.setData({
      areaList: areaList
    });
  },

  /**
   * 返回上一页
   */
  onBackTap: function() {
    wx.navigateBack();
  },

  /**
   * 活动名称变化
   */
  onTitleChange: function(e) {
    this.setData({
      'formData.title': e.detail
    });
  },

  /**
   * 活动费用变化
   */
  onCashChange: function(e) {
    this.setData({
      'formData.cash': e.detail
    });
  },

  /**
   * 限制名额变化
   */
  onLimitChange: function(e) {
    this.setData({
      'formData.limit': e.detail
    });
  },

  /**
   * 详细地址变化
   */
  onAddressChange: function(e) {
    this.setData({
      'formData.address': e.detail
    });
  },

  /**
   * 地区选择变化
   */
  // 显示地区选择器
  showAreaPicker: function() {
    this._initAddressInfo();
    this.setData({
      showAreaPicker: true
    });
  },

  // 构建areaList数据格式，供van-area组件使用
  getAreaList: function() {
    const { provinceData, cityData, districtData } = this.data;
    
    const areaList = {
      province_list: {},
      city_list: {},
      county_list: {}
    };
    
    // 构建省份数据
    provinceData.forEach(province => {
      areaList.province_list[province.id] = province.areaname
    });
    
    // 构建城市数据
    cityData.forEach(city => {
      areaList.city_list[city.id] = city.areaname;
    });
    
    // 构建区县数据
    districtData.forEach(district => {
      areaList.county_list[district.id] = district.areaname;
    });
    
    return areaList;
  },

  // 隐藏地区选择器
  hideAreaPicker: function() {
    this.setData({
      showAreaPicker: false
    });
  },

  // 地区选择变化
  onAreaConfirm: function(e) {
    console.log(e)
    const { values } = e.detail;
    this.setData({
      'formData.province_id': values[0]?.code,
      'formData.city_id': values[1]?.code,
      'formData.district_id': values[2]?.code,
      regionText: values.map(item => item.name).join(' ')
    });
    // 选择完成后关闭弹窗
    this.hideAreaPicker();
  },

  /**
   * 图片上传成功后
   */
  afterRead: function(e) {
    wx.showLoading({
      title: '上传中',
    })
    let {
      file
    } = e.detail;
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      formData: null,
      success: (res) => {
        wx.hideLoading();
        let _res = JSON.parse(res.data);
        this.setData({
          'formData.thumb': _res.data.img_url,
          'thumb': _res.data.img_url
        })
      },
      fail: (err) => {
        wx.hideLoading()
      }
    });
  },

  /**
   * 删除图片
   */
  deleteImage: function() {
    this.setData({
      'formData.thumb': '',
      'formData.fileList': []
    });
  },

  /**
   * 显示报名开始日期选择器
   */
  showRegistrationStartPicker: function() {
    this.setData({
      showRegistrationStartPicker: true
    });
  },

  /**
   * 关闭报名开始日期选择器
   */
  closeRegistrationStartPicker: function() {
    this.setData({
      showRegistrationStartPicker: false
    });
  },

  /**
   * 确认报名开始日期
   */
  confirmRegistrationStartTime: function(e) {
    const date = new Date(e.detail);
    const formattedDate = this.formatDate(date);
    this.setData({
      'formData.registration_time': formattedDate,
      showRegistrationStartPicker: false
    });
  },

  /**
   * 显示报名结束日期选择器
   */
  showRegistrationEndPicker: function() {
    this.setData({
      showRegistrationEndPicker: true
    });
  },

  /**
   * 关闭报名结束日期选择器
   */
  closeRegistrationEndPicker: function() {
    this.setData({
      showRegistrationEndPicker: false
    });
  },

  /**
   * 确认报名结束日期
   */
  confirmRegistrationEndTime: function(e) {
    const date = new Date(e.detail);
    const formattedDate = this.formatDate(date);
    this.setData({
      'formData.registration_end_time': formattedDate,
      showRegistrationEndPicker: false
    });
  },

  /**
   * 显示活动开始日期选择器
   */
  showActivityStartPicker: function() {
    this.setData({
      showActivityStartPicker: true
    });
  },

  /**
   * 关闭活动开始日期选择器
   */
  closeActivityStartPicker: function() {
    this.setData({
      showActivityStartPicker: false
    });
  },

  /**
   * 确认活动开始日期
   */
  confirmActivityStartTime: function(e) {
    const date = new Date(e.detail);
    const formattedDate = this.formatDate(date);
    this.setData({
      'formData.start_time': formattedDate,
      showActivityStartPicker: false
    });
  },

  /**
   * 显示活动结束日期选择器
   */
  showActivityEndPicker: function() {
    this.setData({
      showActivityEndPicker: true
    });
  },

  /**
   * 关闭活动结束日期选择器
   */
  closeActivityEndPicker: function() {
    this.setData({
      showActivityEndPicker: false
    });
  },

  /**
   * 确认活动结束日期
   */
  confirmActivityEndTime: function(e) {
    const date = new Date(e.detail);
    console.log(e.detail);
    const formattedDate = this.formatDate(date);
    this.setData({
      'formData.end_time': formattedDate,
      showActivityEndPicker: false
    });
  },

  /**
   * 格式化时间
   */
  formatDate: function(date) {
    return `${date.getYear()+1900}-${date.getMonth() + 1}-${date.getDate()}`;
  },

  /**
   * 表单验证
   */
  validateForm: function() {
    const { formData } = this.data;
    
    if (!formData.title) {
      wx.showToast({ title: '请输入活动名称', icon: 'none' });
      return false;
    }
    
    if (!formData.thumb) {
      wx.showToast({ title: '请上传活动图片', icon: 'none' });
      return false;
    }
    
    if (!formData.registration_time) {
      wx.showToast({ title: '请选择报名开始时间', icon: 'none' });
      return false;
    }
    
    if (!formData.registration_end_time) {
      wx.showToast({ title: '请选择报名结束时间', icon: 'none' });
      return false;
    }
    
    if (!formData.start_time) {
      wx.showToast({ title: '请选择活动开始时间', icon: 'none' });
      return false;
    }
    
    if (!formData.end_time) {
      wx.showToast({ title: '请选择活动结束时间', icon: 'none' });
      return false;
    }
    
    if (!formData.limit) {
      wx.showToast({ title: '请输入限制名额', icon: 'none' });
      return false;
    }
    
    if (!formData.province_id || !formData.city_id || !formData.district_id) {
      wx.showToast({ title: '请选择活动地址', icon: 'none' });
      return false;
    }
    
    return true;
  },

  /**
   * 提交表单
   */
  onSubmit: function() {
    if (!this.validateForm()) {
      return;
    }
    
    const { formData } = this.data;
    
    var that = this;
    app._getNetWork({
      url: app.getNetAddresss("plugin.commerce.api.commerce-activity.create-activity"),
      data: formData,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.hideLoading();
          wx.showToast({ title: '发布成功' });
          
          // 延迟返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }else{
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {},
      state: true
    });
  }
});